using System.Data.SqlClient;
using System.Data;
using System.IO;
using System.Reflection;
namespace Destra.Tools.DACGenerator.Resources
{
    public static class ExecuteEmbeddedResource
    {

        /// <summary>
        /// Retrieves the specified manifest resource stream from the executing assembly as a string.
        /// </summary>
        /// <param name="name">Name of the resource to retrieve.</param>
        /// <returns>The value of the specified manifest resource.</returns>
        internal static string GetResource(string name)
        {
            using (StreamReader streamReader = new StreamReader(Assembly.GetExecutingAssembly().GetManifestResourceStream(name)))
            {
                return streamReader.ReadToEnd();
            }
        }

        /// <summary>
        /// Retrieves the specified manifest resource stream from the executing assembly as a string, 
        /// replacing the specified old value with the specified new value.
        /// </summary>
        /// <param name="name">Name of the resource to retrieve.</param>
        /// <param name="oldValue">A string to be replaced.</param>
        /// <param name="newValue">A string to replace all occurrences of oldValue.</param>
        /// <returns>The value of the specified manifest resource, with all instances of oldValue replaced with newValue.</returns>
        internal static string GetResource(string name, string oldValue, string newValue)
        {
            string returnValue = GetResource(name);

            return returnValue.Replace(oldValue, newValue);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="connectionString"></param>
        /// <param name="resourceName"></param>
        public static void ExecuteEmbeddedSqlFile(string connectionString, string resourceName, params string[] formatStringValues)
        {
            string sql = GetResource("Destra.Tools.DACGenerator.Resources." + resourceName);
            if (formatStringValues != null)
            {
                sql = string.Format(sql, formatStringValues);
            }

            using (SqlConnection connection = new SqlConnection(connectionString))
            {
                using (SqlCommand command = new SqlCommand(sql))
                {
                    command.Connection = connection;
                    command.Connection.Open();
                    command.CommandType = CommandType.Text;
                    command.ExecuteNonQuery();
                }
            }


        }

    }
}
